import { useState, useEffect } from 'react';
import Cookies from 'js-cookie';
import { Button, Modal, Select, Input, Table } from 'antd';
import { InbizIcon, deepClone } from '@inbiz/utils';
import Pagination from '@inbiz/basic/Pagination';
import { uid } from '@inbiz/shared';
import { TextWidget, getMessage } from '@inbiz/react';
import { getApplyCategory } from './services';
import './index.less';

export default function ProcessGroup(props: { onChange: any; value?: { selectedRows: never[]; groupGuid: string; } | undefined; }) {
  const {
    onChange,
    value = {
      selectedRows: [],
      groupGuid: '',
    },
  } = props;
  const [visible, $visible] = useState(false);
  const [searchValue, $searchValue] = useState('');
  const [selectedRowKeys, $selectedRowKeys] = useState(['']);
  const [selectedRows, $selectedRows] = useState([]);
  const [dataSource, $dataSource] = useState<
    {
      id: '';
      groupName: '';
    }[]
  >([]);
  const [pageData, $pageData] = useState({
    pageIndex: 1,
    pageSize: 10,
    total: 0,
  });

  const dataColumns = [
    {
      title: getMessage('processCenter.processGroup'),
      dataIndex: 'groupName',
    },
  ];

  const getGroups = (groupName: string, page: object) => {
    getApplyCategory({ groupName, ...page }).then((res) => {
      if (res && res.details && res.details.rows) {
        $dataSource([...res.details.rows]);
        $pageData({
          pageIndex: page ? page.pageIndex : pageData.pageIndex,
          pageSize: page ? page.pageSize : pageData.pageSize,
          total: res.details.total,
        });
      } else {
        $dataSource([]);
      }
    });
  };

  const onSearch = (v: string) => {
    $searchValue(v);
    $pageData((preState) => {
      return {
        ...preState,
        pageIndex: 1
      }
    })
    getGroups(v, {
      pageIndex: 1,
      pageSize: pageData.pageSize,
    });
  };
  const handleRowClick = (RowKeys: any[] | ((prevState: string[]) => string[]), Rows: any[] | ((prevState: never[]) => never[])) => {
    $selectedRowKeys(RowKeys);
    $selectedRows(Rows);
  };
  const onCancel = () => {
    $visible(false);
    $searchValue('');
    if (value.selectedRows) {
      const arr = value.selectedRows.map((item: { value: any; id: any; }) => item.value || item.id);
      $selectedRowKeys(arr);
    }
  };

  /***
   *  设置needSave 是否需要保存
   *  设置groupGuid, 保存流程分组的key值, 第一次是''
   *  rows是操作之后的数据, values.selectedRows是设计器的数据, 如果两个length都是0 说明是第一次, 就什么也不做
   *  如果两个长度相同, 就要对比有没有改变
   *  先把两个的id都提出来, 以为Select的labelInValue属性, id可能是value, 也可能是id
   *  对比方法是新的id值里面有没有跟旧的id不一样的, 只要有一个不一样就行, 所以用some
   *  如果需要保存就生成新的groupGuid
   */

  const saveData = (rows: any[]): any => {
    let needSave = false;
    let groupGuid = value.groupGuid ?? '';
    if (value.selectedRows && rows.length == 0 && value.selectedRows.length == 0) {
      return false;
    }
    if (value.selectedRows && rows.length == value.selectedRows.length) {
      const newkeys = rows.map((item: { value: any; id: any; }) => item.value || item.id);
      const oldkeys = value.selectedRows.map((item: { value: any; id: any; }) => item.value || item.id);
      needSave = newkeys.some((i: any) => oldkeys.some((j: any) => j !== i));
    } else {
      needSave = true;
    }
    if (needSave) {
      groupGuid = uid(32);
    }

    onChange({
      selectedRows: rows,
      groupGuid,
    });

    localStorage.setItem('needSaveProcessGroup', needSave ? '1' : '0')
  };

  const onOk = () => {
    saveData(selectedRows);
    onCancel();
  };
  const handleChange = (val: any) => {
    saveData(val);
  };

  const handleRowSelection = (record: { id: any; }) => {
    const existKey = selectedRowKeys.includes(record.id);
    if (existKey) {
      const newkeys = deepClone(selectedRowKeys);
      const newrows = deepClone(selectedRows);
      const index = selectedRowKeys.indexOf(record.id);
      newkeys.splice(index, 1);
      newrows.splice(index, 1);
      handleRowClick(newkeys, newrows);
    } else {
      handleRowClick([...selectedRowKeys, record.id], [...selectedRows, record]);
    }
  };

  useEffect(() => {
    if (visible) {
      getGroups('', {
        pageIndex: pageData.pageIndex,
        pageSize: pageData.pageSize,
      });
    }
  }, [visible]);

  useEffect(() => {
    if (value.selectedRows) {
      const arr = value.selectedRows.map((item: { value: any; id: any; }) => item.value || item.id);
      $selectedRows(value.selectedRows);
      $selectedRowKeys(arr);
    }
  }, [value]);

  return (
    <div className="processGroupConfig">
      <Button type="primary" onClick={() => $visible(true)}>
        <TextWidget>processCenter.pick</TextWidget>
      </Button>
      {value?.selectedRows && value?.selectedRows.length > 0 && (
        <Select
          value={value?.selectedRows?.map((item: { id: any; value: any; groupName: any; label: any; }) => ({
            ...item,
            key: item.id || item.value,
            label: item.groupName || item.label,
          }))}
          labelInValue
          mode="multiple"
          onChange={handleChange}
          dropdownStyle={{ display: 'none' }}
        />
      )}
      <Modal
        className="groupModal"
        width={800}
        title={getMessage('processCenter.selectGroup')}
        visible={visible}
        destroyOnClose
        okText="确定"
        onCancel={onCancel}
        footer={
          <div className="modalFooter">
            <p>
              <span>
                已选择<a> {selectedRowKeys.length}</a>{' '}
                {/* <InbizIcon type="icon-zhankai2" style={{ fontSize: 12, color: '#000' }} /> */}
              </span>
            </p>
            <div>
              <Button onClick={onCancel}>
                <TextWidget>global.cancel</TextWidget>
              </Button>
              <Button onClick={onOk} type="primary">
                <TextWidget>global.save</TextWidget>
              </Button>
            </div>
          </div>
        }
      >
        <Input
          placeholder={getMessage('processCenter.inputCondition')}
          onPressEnter={(e) => onSearch(searchValue)}
          onChange={(e) => $searchValue(e.target.value)}
          suffix={
            <InbizIcon
              onClick={() => onSearch(searchValue)}
              type="icon-ic-search"
              style={{ fontSize: 16, color: '#8a8a8a' }}
            />
          }
          value={searchValue}
          style={{ width: 260, borderRadius: 4 }}
        />
        <div className="tableContainer">
          <Table
            columns={dataColumns}
            dataSource={dataSource}
            scroll={{ y: 250 }}
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onSelect: (record) => {
                handleRowSelection(record);
              },
              onSelectAll: (selected, _selectedRows, changeRows: any) => {
                if(!selected){
                  let _dataSource = dataSource?.map((item: any) => item?.id);
                  let _selectedRowKeys = selectedRowKeys?.filter((item2: string) => !_dataSource?.includes(item2));
                  let __selectedRows = selectedRows?.filter((item3: any) => _selectedRowKeys?.includes(item3?.id));
                  handleRowClick(_selectedRowKeys, __selectedRows);
                } else {
                  let __selectedRows = selectedRows?.concat(changeRows);
                  const newArr = new Set(__selectedRows);
                  __selectedRows = [...newArr];
                  let _keys = __selectedRows?.map(item => item?.id);
                  handleRowClick(_keys, __selectedRows);
                }
              },
            }}
            onRow={(record: { id: string }) => {
              return {
                onClick: () => {
                  handleRowSelection(record);
                },
              };
            }}
            pagination={false}
          />
          <Pagination
            options={[10, 20, 30, 40, 50]}
            total={pageData.total}
            style={{ position: 'absolute', bottom: 0, fontSize: 12 }}
            current={pageData.pageIndex}
            size='small'
            onChange={({ current, pageSize }) => {
              $pageData({
                ...pageData,
                pageIndex: current,
                pageSize: pageSize,
              });
              getGroups(searchValue, {
                pageIndex: current,
                pageSize,
              });
            }}
          />
        </div>
      </Modal>
    </div>
  );
}
